package com.leyou.cart.interceptors;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.holder.UserHolder;
import com.leyou.common.utils.CookieUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author 虎哥
 */
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws UnsupportedEncodingException {
        // 获取cookie中的token
        String token = CookieUtils.getCookieValue(request, "LY_TOKEN");
        // 从token中获取载荷
        Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, UserInfo.class);
        // 获取用户
        UserInfo user = payload.getUserInfo();
        // 保存用户信息
        UserHolder.setUserInfo(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }
}
